package com.apes.fn.scm.lossSale;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 定损退货
 * @Author wuq
 * @Date 2021-12-16
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = LossSaleReturn.CONST_TABLE_NAME)
public class LossSaleReturn extends Model {
    public final static String CONST_TABLE_NAME = "loss_Sale_return";

    @Id
    @Column(name = "id", nullable = false, length = 24)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "定损退货单", padding = 5, prefix = "DR%(company)%(yy)%(month)", useDateRange = true)
    @Comment("退货单号")
    private String id;

    @Comment("定损单号")
    @Column(name = "loss_Quotation_Id", length = 30)
    private String lossQuotationId;

    @Comment("零售单号")
    @Column(name = "retail_id", length = 30)
    private String retailId;

    @Comment("定损门店公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("定损门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "退货申请"),
            @State(id = "approve", name = "审核"),
            @State(id = "delete", name = "删除"),
            @State(id = "confirm", name = "财务确认"),
            @State(id = "delivered", name = "交货完成"),
            @State(id = "refund", name = "退款完成"),
            @State(id = "done", name = "已完成")})
    @Column(name = "state", length = 10, nullable = false)
    private String state = "sent";

    @Comment("订单备注")
    @Column(name = "remark", length = 120)
    private String remark;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amtTotal = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核

    @Comment("审批日期")
    @Column(name = "date_approve")
    private Date dateApprove;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteId; //删除人

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;    // 删除日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "confirm_id", referencedColumnName = "id")
    @Comment("确认人")
    private PartyRole confirmId; // 确认人

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "confirm_date")
    @Comment("确认日期")
    private Date confirmDate;    // 确认日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "refund_id", referencedColumnName = "id")
    @Comment("确认人")
    private PartyRole refundId; // 退款人

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "refund_Date")
    @Comment("退款日期")
    private Date refundDate;    // 退款日期

    @OneToMany(mappedBy = "lossSaleReturn", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<LossSaleReturnItem> returnItems = new HashSet(); //订单行

    public Set<LossSaleReturnItem> getReturnItems() {
        if (returnItems == null) return new HashSet();
        for (LossSaleReturnItem item : returnItems) {
            if (item.getQtyDelivered() < 0) throw new RuntimeException("退回数量不允许为负数！");
            item.setLossSaleReturn(this);
           }
        return returnItems;
    }

    @Transient
    @States(name = "需要收货", values = {
            @State(id = "yes", name = "需收货"),
            @State(id = "no", name = "无需收货")})
    private String needDelivery;

    public String getNeedDelivery() {
        Set<LossSaleReturnItem> returnItems = this.returnItems.stream()
                .filter(returnItem -> LogicalUtil.notIn(returnItem.getProduct().getType(), "aut"))
                .collect(Collectors.toSet());
        return returnItems.isEmpty() ? "no" : "yes";
    }

    @Comment("需退款标记")
    @States(name = "需要退款", values = {
            @State(id = "yes", name = "需退款"),
            @State(id = "no", name = "无需退款")})
    @Column(name = "refund")
    private String refund = "no";

    @Transient
    private Map creatorParty;

    public Map getCreatorParty(){
        if (getCreator() == null) return null;
        return MapUtil.mapped(SpringManager.getBean(PartyRoleRepository.class).findOne(getCreator()));
    }

}
